package com.partner.partnerback.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnectionCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@SuppressWarnings(value = {"unchecked","rawtypes"})
@Component
@Slf4j
public class RedisUtils {

    private static RedisTemplate<String, Object> staticRedisTemplate;

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisUtils (RedisTemplate<String, Object> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    /**
     * springboot启动成功之后会调用这个方法
     * 初始化 staticRedisTemplate 将redisTemplate赋值给它
     */
    @PostConstruct
    public void initRedis(){

        staticRedisTemplate = redisTemplate;
    }

    /**
     * 缓存基本的对象，Integer，String，实体类等
     * @param key
     * @param value
     * @param <T>
     */
    public static <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit){
        staticRedisTemplate.opsForValue().set(key, value,timeout, timeUnit);
    }

    /**
     * 获取缓存对象
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T getCacheObject(final String key){
        return (T) staticRedisTemplate.opsForValue().get(key);
    }

    /**
     * 删除单个对象
     * @param key
     * @return
     */
    public static boolean deleteObject(final String key){
        return Boolean.TRUE.equals(staticRedisTemplate.delete(key));
    }

    /**
     * 获取单个key的过期时间
     * @param key
     * @return
     */
    public static Long getExpireTime(final String key){
        return staticRedisTemplate.getExpire(key);
    }

    /**
     * 发送ping命令给redis
     */
    public static void ping(){
        String execute = staticRedisTemplate.execute(RedisConnectionCommands::ping);
        log.info("Redis ping ==== {}", execute);
    }

}
